package com.white.commonlib.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import com.white.commonlib.manager.LogManager;
import com.white.ndkmaster.NativeX;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

/**
 * Created by yutf on 2017/5/26 0026.
 *
 */

public class AppUtils
{

    private static final String QQLite = "com.tencent.qqlite";
    private static final String QQFULL = "com.tencent.mobileqq";
    public static final String WX = "com.tencent.mm";
    private static final String WEIBO = "com.sina.weibo";

    public static final int PLAT_QQ = 0;
    public static final int PLAT_WX = 1;
    public static final int PLAT_SINA = 2;

    private static final String SCHEME = "package";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
     */
    private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
     */
    private static final String APP_PKG_NAME_22 = "pkg";
    /**
     * InstalledAppDetails所在包名
     */
    private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";
    /**
     * InstalledAppDetails类名
     */
    private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

    /***
     * 判断某个app是否安装，该方法支持微信，qq，新浪微博判读
     * @param context
     * @param app     PLAT_QQ, PLAT_WX, PLAT_SINA
     * @return
     */
    public static boolean isAppInstalled(Context context, int app)
    {
        String platform = "";
        switch (app)
        {
            case PLAT_QQ:
                platform = "";
                break;
            case PLAT_SINA:
                platform = WEIBO;
                break;
            case PLAT_WX:
                platform = WX;
                break;
        }
        PackageManager pm = context.getPackageManager();
        if(pm != null)
        {
            List<PackageInfo> packs = pm.getInstalledPackages(0);
            for (int i = 0; i < packs.size(); i++)
            {
                PackageInfo p = packs.get(i);
                String pn = p.packageName;
                if(TextUtils.isEmpty(platform))
                {
                    if (QQFULL.equalsIgnoreCase(pn) || QQLite.equalsIgnoreCase(pn))
                    {
                        return true;
                    }
                }else
                {
                    if (pn.equalsIgnoreCase(platform))
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static void startQQ(Context mContext,String qqnum)
    {
        startQQ(mContext, 1, qqnum);
    }

    public static void startQQ(Context mContext, int type, String qqnum)
    {
        if(!isAppInstalled(mContext, AppUtils.PLAT_QQ))
        {
            PhoneUtils.toast(mContext, "您尚未安装手机QQ");
            return;
        }
        String url = null;
        switch (type)
        {
            case 1:
                // 直接进入QQ聊天(对QQ号)
                url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qqnum;
                break;
            case 2:
                // 打开个人介绍界面（对QQ号）
                url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                        + "&card_type=person&source=qrcode";
                break;
            case 3:
                // 打开QQ群介绍界面(对QQ群号)
                url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" + qqnum
                        + "&card_type=group&source=qrcode";
                break;
            default:
                break;
        }
        mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }


    /***
     * 根据提供的包名判断是否存在该app
     * @param context
     * @param appPackageName
     * @return
     */
    public static boolean isAppInstalled(Context context, String appPackageName)
    {
        if(TextUtils.isEmpty(appPackageName))
        {
            return false;
        }
        PackageManager pm = context.getPackageManager();
        if(pm != null)
        {
            List<PackageInfo> packs = pm.getInstalledPackages(0);
            for (int i = 0; i < packs.size(); i++)
            {
                PackageInfo p = packs.get(i);
                String pn = p.packageName;
                if (pn.equalsIgnoreCase(appPackageName))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /***
     * 跳转到浏览器
     * @param ctx
     * @param url
     */
    public static void jumpToBroswer(Context ctx, String url)
    {
        if(!TextUtils.isEmpty(url))
        {
            Intent it = new Intent();
            it.setAction(Intent.ACTION_VIEW);
            it.setData(Uri.parse(url));

            PackageManager pm = ctx.getPackageManager();
            if(pm != null)
            {
                ResolveInfo info = pm.resolveActivity(it, PackageManager.MATCH_DEFAULT_ONLY);
                if(info != null)
                {
                    ctx.startActivity(it);
                }
            }
        }
    }

    /***
     * 跳转到app在应用管理中的信息页面
     * @param context
     */
    public static void jumpAppInfo(Context context)
    {
        String packageName = context.getPackageName();
        Intent intent = new Intent();
        final int apiLevel = Build.VERSION.SDK_INT;
        if (apiLevel >= 9)
        { // 2.3（ApiLevel 9）以上，使用SDK提供的接口
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts(SCHEME, packageName, null);
            intent.setData(uri);
        } else
        { // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
            final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22
                    : APP_PKG_NAME_21);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName(APP_DETAILS_PACKAGE_NAME,
                    APP_DETAILS_CLASS_NAME);
            intent.putExtra(appPkgName, packageName);
        }
        context.startActivity(intent);
    }
//
//    /***
//     * 接口参数加签
//     * @param params
//     * @return
//     */
//    public static void setToken(Context ctx, Map<String, String> params)
//    {
//        if(params != null && params.size() > 0)
//        {
//            Map<String, String> pp = new HashMap<>(params);
//            pp.remove("type");
//            pp.remove("token");
//            Collection<String> c = pp.values();
//            List<String> list = new ArrayList<>(c);
//            Collections.sort(list);
//            StringBuffer sb = new StringBuffer();
//            for (String v : list)
//            {
//                sb.append(v);
//            }
//            String appendedStr = sb.toString();
//            LogManager.e("加密前的串 ==> "+appendedStr);
//            String finalStr = NativeX.md5(ctx, NativeX.md5(appendedStr));
//            params.put("token", finalStr);
//        }
//    }

//    @Deprecated
//    public static String getParamSignDp(Context ctx, String...params)
//    {
//        if(params != null)
//        {
//            int length = params.length;
//            StringBuilder sb = new StringBuilder();
//            for(int i = 0;i<length;i++)
//            {
//                sb.append(params[i]);
//            }
//            LogManager.e("加密前的串为："+sb.toString());
//            return NativeX.md5(ctx, sb.toString() + NativeX.get(ctx, NativeX.AESPWD));
//        }else
//        {
//            return null;
//        }
//    }

    /***
     * 获得设备唯一标识
     * @return
     */
    public static String getDeviceToken(Context mContext)
    {
        String unique = PhoneUtils.getPhoneUniqueNum(mContext);
        String result = NativeX.md5(unique);
        LogManager.e("设备标识：" + result);
        return result;
    }

    /***
     * 获取手机型号
     * @return
     */
    public static String getDeviceModel()
    {
        return Build.MODEL;
    }

    public static String getTextFromClip(Context context)
    {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if(clipboardManager != null)
        {
            //判断剪切版时候有内容
            if (!clipboardManager.hasPrimaryClip())
                return null;
            ClipData clipData = clipboardManager.getPrimaryClip();
            //获取 ClipDescription
//            ClipDescription clipDescription = clipboardManager.getPrimaryClipDescription();
//            //获取 lable
//            String lable = clipDescription.getLabel().toString();
            //获取 text
            return clipData.getItemAt(0).coerceToText(context).toString();
        }
        return null;
    }
}
